import { Auth } from '@/auth/auth.schema';
import { getSerializeDateTime } from '@/utils/utils';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Users } from './users.schema';


@Injectable()
export class UsersService {
  private readonly users: Users[];
  constructor(@InjectModel('user') private userModel: Model<Users>) {

  }

  /**
   * 根据账号信息新建用户
   * @param newAuth 账号信息
   */
  async insertNewUser(newAuth: Auth) {
    const newUser = {
      uuid: newAuth.uuid,
      username: newAuth.username,
      createTime: newAuth.createTime,
      updateTime: newAuth.updateTime,
      useStatus: 0
    }
    const createdUser = new this.userModel(newUser);
    createdUser.save(); // 插入数据库
  }

  /**
   * 根据uuid查询用户信息
   * @param uuid 
   * @returns Users
   */
  async getUserInfo(uuid: Users["uuid"]): Promise<Users | undefined> {
    const user = await this.userModel.findOne().where('uuid', uuid).where('useStatus').ne(-1).exec();
    if (!user) {
      throw new InternalServerErrorException({
        errMsg: '该用户名不存在或异常'
      })
    }
    return user;
  }

  /**
   * @param user 根据用户uuid更新用户信息
   */
  async updateUserInfo(user: Users) {
    user.updateTime = getSerializeDateTime()
    const res = await this.userModel.findOneAndUpdate({
      uuid: {
        $eq: user.uuid
      },
      useStatus: {
        $ne: -1
      }
    }, user)
  }
}
